import React, { SetBusiness } from 'react'

// 加载默认首页
import Home from '@/components/Home'

// 总的路由容器
const RouterMap: any = [];

// 不需要合并的文件
var NoNeedAuth = ['index', 'auth']

// 引入当前目录下面的所有的文件
const ModuleFile = require.context('./', true, /.tsx$/);

// 对当前目录下的文件进行加载循环
ModuleFile.keys().map((mod, index) => {
  const ModuleName = mod.replace(/^.\/(.*)\.tsx/, '$1');

  // 忽略文件
  if (!NoNeedAuth.includes(ModuleName)) {
    // 读取这个文件当中的模块内容
    const Content = ModuleFile(mod)

    // 往总的路由容器里面追加
    // RouterMap.push(Array)
    RouterMap.push(...Content.default)

  }
})

const RouterList = () => {
  // 将用户的登录信息记录到状态数据中
  var cookie = React.Cookie.load('business') ? React.Cookie.load('business') : {}
  const [business, SetBusiness] = React.useState(cookie)

  React.Business = business
  React.SetBusiness = SetBusiness

  // 生成一个路由的全局跳转方法
  const navigate = React.Router.useNavigate()
  React.navigate = navigate

  // 构建一个路由守卫的子组件
  const AuthRouter = (props: any) => {
    // 判断当前路由是否有auth的属性
    if (props.auth) {
      //需要判断登录
      //没有属性，说明对象是空，没有登录
      if (Object.getOwnPropertyNames(business).length <= 0) {
        return (
          // 重定向跳转
          <React.Router.Navigate to={"/business/login"} />
        )
      }

      //获取到手机号和id
      let id = business.hasOwnProperty('id') ? business.id : 0
      let mobile = business.hasOwnProperty('mobile') ? business.mobile : ''

      var p: any = React.HTTP.post('/business/check', { id, mobile })

      //异步操作
      p.then((result: any) => {
        if (result.code == 0) {
          React.Cookie.remove('business')

          return (
            <React.Router.Navigate to="/business/login" />
          )
        } else {
          //刷新覆盖一下cookie
          React.Cookie.save('business', result.data)

          return (
            <>
              {props.component}
            </>
          )
        }
      })

      return (
        <>
          {props.component}
        </>
      )
    } else {
      //不需要判断,直接显示当前要访问的组件
      return (
        <>
          {props.component}
        </>
      )
    }
  }

  return (
    <>
      <React.Router.Routes>
        {/* 默认首页 */}
        <React.Router.Route path='/' element={<Home />}></React.Router.Route>

        {/* 其他界面路由 */}
        <React.Router.Route path='/' element={<><React.Router.Outlet /></>}>
          {
            RouterMap.map((item: any, index: any) => {
              return (
                <React.Router.Route key={index} path={item.path} element={<item.component />}>
                  {item.children && item.children.map((son: any, idx: any) => <React.Router.Route key={idx} path={son.path} element={<AuthRouter auth={son.auth ? son.auth : false} component={<son.component />}></AuthRouter>}></React.Router.Route>)}
                </React.Router.Route>
              )
            })
          }
        </React.Router.Route>
      </React.Router.Routes>
    </>
  )
}

export default RouterList
